package com.szj360.spider.downloader;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.openqa.selenium.android.library.Logger;

import com.szj360.utils.ImageBase64Utils;

import us.codecraft.webmagic.downloader.HttpClientDownloader;

public class ImgDownloader extends HttpClientDownloader {
	
	@Override
	protected String getContent(String charset, HttpResponse httpResponse) throws IOException {
		Header[] contentType = httpResponse.getHeaders("Content-Type");
		if("text/html".equals(contentType[0].getValue())){
			if (charset == null) {
	            byte[] contentBytes = IOUtils.toByteArray(httpResponse.getEntity().getContent());
	            String htmlCharset = getHtmlCharset(httpResponse, contentBytes);
	            if (htmlCharset != null) {
	                return new String(contentBytes, htmlCharset);
	            } else {
	                Logger.getLogger().info("Charset autodetect failed, use {} as charset. Please specify charset in Site.setCharset()" + Charset.defaultCharset());
	                return new String(contentBytes);
	            }
	        } else {
	            return IOUtils.toString(httpResponse.getEntity().getContent(), charset);
	        }
		}else if(contentType[0].getValue().startsWith("image")){
			byte[] imageByte = EntityUtils.toByteArray(httpResponse.getEntity());
			String iageStr = ImageBase64Utils.GetImageStr(imageByte);
			return iageStr;	
		}
		if (charset == null) {
            byte[] contentBytes = IOUtils.toByteArray(httpResponse.getEntity().getContent());
            String htmlCharset = getHtmlCharset(httpResponse, contentBytes);
            if (htmlCharset != null) {
                return new String(contentBytes, htmlCharset);
            } else {
                Logger.getLogger().info("Charset autodetect failed, use {} as charset. Please specify charset in Site.setCharset()" + Charset.defaultCharset());
                return new String(contentBytes);
            }
        } else {
            return IOUtils.toString(httpResponse.getEntity().getContent(), charset);
        }
		
//		for (Header header : contentType) {
//			System.out.println(header.getValue());
//		}
		
	}
}
